<?php

namespace app\support;

use Symfony\Component\Console\Input\ArgvInput;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\OutputStyle;
use Symfony\Component\Console\Style\StyleInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

/**
 * @mixin SymfonyStyle
 */
class Printer
{
    /**
     * @var OutputStyle
     */
    private static $outputStyle;

    /**
     * @param mixed ...$data
     * @return void
     */
    public static function print(...$data)
    {
        foreach ($data as $value) {
            if (is_scalar($value)) {
                echo $value;
            } else {
                echo json_encode($value, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
            }
            echo " ";
        }
    }

    /**
     * @return void
     */
    protected static function endStyleLine()
    {
        echo "\033[0m", PHP_EOL;
    }

    /**
     * @param mixed ...$data
     * @return void
     */
    public static function info(...$data)
    {
        self::print(now()->format("Y-m-d H:i:s"), ...$data);
        echo PHP_EOL;
    }

    /**
     * @param mixed ...$data
     * @return void
     */
    public static function error(...$data)
    {
//        self::outputStyle()->block($data, 'ERROR', 'fg=red', now() . " ");
        echo "\033[31m";
        self::print(now()->format("Y-m-d H:i:s"), ...$data);
        self::endStyleLine();
    }


    /**
     * @param mixed ...$data
     * @return void
     */
    public static function success(...$data)
    {
//        self::outputStyle()->block($data, 'OK', 'fg=green', now() . " ");
        echo "\033[32m";
        self::print(now()->format("Y-m-d H:i:s"), ...$data);
        self::endStyleLine();

    }

    /**
     * @param mixed ...$data
     * @return void
     */
    public static function json(...$data)
    {
        self::print($data);
        echo PHP_EOL;
    }

    /**
     * @param mixed ...$data
     * @return void
     */
    public static function errorJson(...$data)
    {
        echo "\033[31m";
        self::print($data);
        self::endStyleLine();
    }

    /**
     * @param mixed ...$data
     * @return void
     */
    public static function successJson(...$data)
    {
        echo "\033[32m";
        self::print($data);
        self::endStyleLine();
    }

    /**
     * @return OutputInterface|StyleInterface
     */
    public static function outputStyle()
    {
        if (self::$outputStyle === null) {
            self::$outputStyle = new SymfonyStyle(new ArgvInput(), new ConsoleOutput());
        }

        return self::$outputStyle;
    }

    /**
     * @param string $name
     * @param array $arguments
     * @return mixed
     */
    public static function __callStatic(string $name, array $arguments)
    {
        return call_user_func_array([self::outputStyle(), $name], $arguments);
    }
}
